package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.AccessRecordService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.common.page.Pagination;
import cn.buildoncloud.labor.workermanapplet.util.AppletUtil;
import cn.buildoncloud.labor.workermanapplet.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.nutz.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * 进出记录管理
 * Description: cn.buildoncloud.labor.workermanapplet.business.modules.controller
 * Created by CuiZibo on 2018/11/16 14:22
 */
@RestController
@RequestMapping("/accessRecord")
public class AccessRecordController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AccessRecordService accessRecordService;

    @Autowired
    private Dao dao;

    /**
     * 进出记录列表
     * @param name
     * @param passed
     * @param personType
     * @param projectId
     * @param date
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("/queryAccessRecordList")
    public Object queryAccessRecordList(@RequestParam(value = "name", required = false) String name,
                                        //放行 true 1 不放行 false 0
                                        @RequestParam(value = "passed", required = false) Integer passed,
                                        //人员类型 1工友 2管理人员
                                        @RequestParam(value = "personType", required = false) Integer personType,
                                        @RequestParam(value = "projectId", required = true) String projectId,
                                        @RequestParam(value = "date", required = false) String date,
                                        @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        try {
            if (StringUtil.isNotBlank(projectId)) {
                Pagination pagination = accessRecordService.queryAccessRecordList(name, passed, personType, projectId, date, pageNo, pageSize);
                return Result.success(Constant.API_OPERATION_SUCCESS, pagination);
            }
            return Result.error(Constant.API_OPERATION_FAILED);
        } catch (Exception e) {
            log.error("accessRecord/queryAccessRecordList: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    /**
     * 进出人员详情
     * @param id
     * @param projectId
     * @param personType
     * @return
     */
    @RequestMapping("/queryAccessRecordDetail")
    public Object queryAccessRecordDetail(@RequestParam(value = "id", required = true) String id,
                                          @RequestParam(value = "projectId", required = true) String projectId,
                                          //人员类型 1工友 2管理人员
                                          @RequestParam(value = "personType", required = true) int personType) {
        try {
            Map data = accessRecordService.queryAccessRecordDetail(id, projectId, personType);

            return Result.success(Constant.API_OPERATION_SUCCESS, data);
        } catch (Exception e) {
            log.error("accessRecord/queryAccessRecordDetail: ", e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }
    }

    /*
        @RequestMapping("/showFileByBase64")
        public Object showFileByBase64(@RequestParam("photoPathByBase64") String photoPathByBase64,
                                       HttpServletResponse response) {

            if (StringUtil.isBlank(photoPathByBase64)) {
                return Result.error("图片路径为空");
            }
            File file = null;
            String fileStr = "";
            try {
                String path = new String(Base64.decodeBase64(photoPathByBase64));
                if (StringUtil.isNotBlank(path)) {
                    file = new File(path);
                    fileStr = FileUtil.fileToBase64(file);
                    return Result.success(Constant.API_OPERATION_SUCCESS, "data:image/jpeg;base64,"+fileStr);
                }
                return Result.error("图片转换失败");
            } catch (Exception ex) {
                log.error("accessRecord/showFileByBase64: ", ex);
                return Result.error("图片转换失败");
            }

        }*/

    /**
     * 显示进出人员照片
     * @param photoPathByBase64
     * @param openId
     * @param response
     */
    @RequestMapping("/showFileByBase64")
    public void showFileByBase64(@RequestParam("photoPathByBase64") String photoPathByBase64,
                                 @RequestParam("openId") String openId,
                                 HttpServletResponse response) {

        InputStream in = null;
        OutputStream out = null;
        try {
            Result result = AppletUtil.checkOpenId(openId, dao);
            if (result.getCode() == 1) {
                AppletUtil.returnJson(response, JSONObject.toJSONString(result));
                return;
            }
            String path = new String(Base64.decodeBase64(photoPathByBase64));
            if (StringUtil.isNotBlank(path)) {
                response.reset();
                response.setHeader("Content-Disposition", "");
                response.setHeader("Pragma", "No-cache");
                response.setHeader("Cache-Control", "No-cache");
                response.setDateHeader("Expires", 0);
                in = new FileInputStream(path);
                out = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            }
        } catch (Exception ex) {
            log.error("accessRecord/showFileByBase64: ", ex);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ex) {

            }
        }
    }
}
